/*
 * Copyright 2012 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.ekuma.android.ui.scan.history.upload;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import cn.ekuma.android.ui.scan.history.HistoryManager;
import cn.ekuma.epos.datalogic.DataLogicPDA;
import cn.ekuma.epos.datalogic.I_DataLogicSales;
import cn.ekuma.epos.ui.android.R;

import com.caucho.hessian.client.HessianRuntimeException;
import com.openbravo.bean.pda.LocalHistory;
import com.openbravo.data.basic.BasicException;

import java.util.Date;
import java.util.List;

public final class LocalHistoryActivity extends ListActivity {

  private static final int SEND_ID = Menu.FIRST;
  private static final int CLEAR_ID = Menu.FIRST + 1;
  private static final int DELETE_ID = Menu.FIRST + 2;
  
  private static final int CHANGE_DAIL = Menu.FIRST + 3;

  private HistoryManager historyManager;
  private LocalHistoryAdapter adapter;
  List<LocalHistory> items;

    @Override
  protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    this.historyManager = new HistoryManager(this);  
    adapter = new LocalHistoryAdapter(this);

    setListAdapter(adapter);
    ListView listview = getListView();
    registerForContextMenu(listview);
    getActionBar().setDisplayHomeAsUpEnabled(true);
  }

  @Override
  protected void onResume() {
    super.onResume();
   
   	
    items = historyManager.buildLocalHistorys();
    adapter.clear();
    for (LocalHistory item : items) {
      adapter.add(item);
    }
     if(items.isEmpty()){
    	 LocalHistory temp=new LocalHistory();
    	 temp.setCsvValue("");
    	 temp.setCreateDate(new Date());
    	 adapter.add(temp);
     }
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
	  AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setMessage(adapter.getItem(position).getCsvMore());
      builder.setCancelable(true);
      builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int i2) {
        	dialog.dismiss();
        }
      });
      builder.setNegativeButton(R.string.button_cancel, null);
      builder.show();
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu,
                                  View v,
                                  ContextMenu.ContextMenuInfo menuInfo) {
    int position =((AdapterView.AdapterContextMenuInfo) menuInfo).position;
      if(!items.isEmpty()) {
          menu.add(Menu.NONE, position, DELETE_ID, R.string.history_clear_one_history_text);
          menu.add(Menu.NONE, position, SEND_ID, R.string.history_send);

          menu.add(Menu.NONE, position, CHANGE_DAIL, R.string.history_change_dail);
      }
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    int position = item.getItemId();
    final LocalHistory temp=adapter.getItem(position);
    switch(item.getOrder()){
       case SEND_ID:
    	   upload(temp);
    	   break;
       case DELETE_ID:
    	   historyManager.deleteLocalHistory(temp);
    	   adapter.remove(temp);
    	   break;
       case CHANGE_DAIL:
    	   AlertDialog.Builder builder = new AlertDialog.Builder(LocalHistoryActivity.this);  
   	    LayoutInflater factory = LayoutInflater.from(this);  
   	    final View textEntryView = factory.inflate(R.layout.agg_input_number_dialog, null);  
   	    final EditText inputNumber = (EditText) textEntryView.findViewById(R.id.edit_input_number_dialog);
   	    builder.setIcon(R.drawable.shopper_icon);  
   	    builder.setTitle("请输入说明");  
   	    builder.setView(textEntryView);  
   	    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {  
   	        public void onClick(DialogInterface dialog, int whichButton) {  
   	            String memo=inputNumber.getText().toString();
   	             temp.setMemo(memo);
   	            historyManager.addHistoryItemDetails(temp.getId(),memo);
   	        }  
   	    });  
   	    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {  
   	        public void onClick(DialogInterface dialog, int whichButton) {  
   	  
   	        }  
   	    });  
   	    inputNumber.setText(temp.getMemo());
   	    builder.create().show();     
    }
    return true;
  }

  private void upload(final LocalHistory temp){
	  final ProgressDialog dialog = ProgressDialog.show(this, "", 
		        "上传数据，请稍等 …", true, true); 
		Thread t = new Thread(new Runnable() { 
		    public void run() {
		        try { 
		        	   I_DataLogicSales basic  =DataLogicPDA.getDLSales();
                       basic.insert(temp);
		         	} catch (HessianRuntimeException e){	
		         		System.out.print(e);
		         	}catch (BasicException e) {
		         		System.out.print(e);
		         	}
		        dialog.dismiss(); 
		    } 
		}); 
		t.start();
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    if (historyManager.hasHistoryItems()) {
      menu.add(0, CLEAR_ID, 0, R.string.history_clear_text).setIcon(android.R.drawable.ic_menu_delete);
      return true;
    }
    return false;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case CLEAR_ID:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.msg_sure);
        builder.setCancelable(true);
        builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int i2) {
            historyManager.clearLocalHistory();
            dialog.dismiss();
            adapter.clear();
            LocalHistory temp=new LocalHistory();
       	    temp.setCsvValue("");
       	    temp.setCreateDate(new Date());
       	    adapter.add(temp);
          }
        });
        builder.setNegativeButton(R.string.button_cancel, null);
        builder.show();
        break;
      case android.R.id.home:
                    finish();
                    return true;
      default:
        return super.onOptionsItemSelected(item);
    }
    return true;
  }

}
